package com.mdd.front.service.order.impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mdd.common.entity.order.Order;
import com.mdd.common.entity.order.OrderAccept;
import com.mdd.common.entity.order.OrderAcceptDetails;
import com.mdd.common.entity.order.OrderGoods;
import com.mdd.common.mapper.order.OrderAcceptDetailsMapper;
import com.mdd.common.mapper.order.OrderAcceptMapper;
import com.mdd.common.mapper.order.OrderGoodsMapper;
import com.mdd.common.mapper.order.OrderMapper;
import com.mdd.common.util.ServiceUtils;
import com.mdd.common.util.StringUtils;
import com.mdd.front.JzFrontThreadLocal;
import com.mdd.front.service.order.IOrderAcceptService;

import com.mdd.front.validate.common.PageValidate;
import com.mdd.front.validate.order.OrderAcceptCreateValidate;
import com.mdd.front.validate.order.OrderAcceptSearchValidate;
import com.mdd.front.validate.order.OrderAcceptUpdateValidate;
import com.mdd.front.vo.order.OrderAcceptDetailVo;
import com.mdd.front.vo.order.OrderAcceptListedVo;
import com.mdd.common.core.PageResult;


import com.mdd.common.util.TimeUtils;

import com.mdd.front.vo.order.completedList.CompletedListVo;
import com.mdd.front.vo.order.completedList.CustomerReview;
import com.mdd.front.vo.order.completedList.OrderTimeline;
import com.mdd.front.vo.order.reservedList.*;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.*;

/**
 * 接单实现类
 * @author LikeAdmin
 */
@Service
public class OrderAcceptServiceImpl implements IOrderAcceptService {
        
    @Resource
    OrderAcceptMapper orderAcceptMapper;
    @Resource
    OrderMapper orderMapper;

    @Resource
    OrderAcceptDetailsMapper orderAcceptDetailsMapper;
    @Resource
    OrderGoodsMapper orderGoodsMapper;
    /**
     * 接单列表
     *
     * @author LikeAdmin
     * @param pageValidate 分页参数
     * @param searchValidate 搜索参数
     * @return PageResult<OrderAcceptListedVo>
     */
    @Override
    public PageResult<OrderAcceptListedVo> list(PageValidate pageValidate, OrderAcceptSearchValidate searchValidate) {
        Integer page  = pageValidate.getPageNo();
        Integer limit = pageValidate.getPageSize();
        Integer userId = JzFrontThreadLocal.getUserId();
        QueryWrapper<OrderAccept> queryWrapper = new QueryWrapper<>();
//        queryWrapper.orderByDesc("id");
        // 订单状态
        if (StringUtils.isNotNull(searchValidate.getStatus())) {
            queryWrapper.eq("order_status", searchValidate.getStatus());
        }else {
            queryWrapper
                    .ge("status", 0)
                    .le("status", 2);
        }
        queryWrapper.eq("is_delete", 0).eq("user_id", userId).orderByDesc("create_time");


        IPage<OrderAccept> iPage = orderAcceptMapper.selectPage(new Page<>(page, limit), queryWrapper);

        List<OrderAcceptListedVo> list = new LinkedList<>();
        for(OrderAccept item : iPage.getRecords()) {
//            List<OrderGoods> orderGoodsList = orderGoodsMapper.selectList(new QueryWrapper<OrderGoods>().eq("order_id", record.getId()).select("id,goods_id,goods_name,goods_sku_id,goods_sku_value,goods_image,goods_num,goods_price," + "goods_original_price,need_pay_money,goods_money"));

            Order order = orderMapper.selectOne(new QueryWrapper<Order>().eq("id", item.getOrderId()).last("LIMIT 1"));
            OrderGoods orderGoods = orderGoodsMapper.selectOne(new QueryWrapper<OrderGoods>().eq("id", order.getId()).last("LIMIT 1"));



            OrderAcceptListedVo vo = new OrderAcceptListedVo();
            vo.setTitle(orderGoods.getGoodsName());
            vo.setPrice(orderGoods.getGoodsPrice());
            vo.setContent(orderGoods.getGoodsSkuValue());
            vo.setStatus(item.getStatus());
            // 订单信息
            JSONObject addressJson = JSONObject.parseObject(order.getAddress());
            String addressDetail = addressJson.getString("address");
            vo.setAddress(addressDetail);
            BeanUtils.copyProperties(item, vo);
            vo.setCreateTime(TimeUtils.timestampToDate(item.getCreateTime()));
            list.add(vo);
        }

        return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), list);
    }

    @Override
    public PageResult<OrderReservedListVo> reservedList(PageValidate pageValidate, OrderAcceptSearchValidate searchValidate) {

        Integer page  = pageValidate.getPageNo();
        Integer limit = pageValidate.getPageSize();
        Integer userId = JzFrontThreadLocal.getUserId();
        QueryWrapper<OrderAccept> queryWrapper = new QueryWrapper<>();
        //已预约（服务中）
        queryWrapper.eq("status", 3);

        queryWrapper.eq("is_delete", 0).eq("user_id", userId).orderByDesc("create_time");


        IPage<OrderAccept> iPage = orderAcceptMapper.selectPage(new Page<>(page, limit), queryWrapper);

        List<OrderReservedListVo> list = new LinkedList<>();
        for(OrderAccept item : iPage.getRecords()) {
//            List<OrderGoods> orderGoodsList = orderGoodsMapper.selectList(new QueryWrapper<OrderGoods>().eq("order_id", record.getId()).select("id,goods_id,goods_name,goods_sku_id,goods_sku_value,goods_image,goods_num,goods_price," + "goods_original_price,need_pay_money,goods_money"));

            Order order = orderMapper.selectOne(new QueryWrapper<Order>().eq("id", item.getOrderId()).last("LIMIT 1"));
            OrderGoods orderGoods = orderGoodsMapper.selectOne(new QueryWrapper<OrderGoods>().eq("id", order.getId()).last("LIMIT 1"));



            OrderReservedListVo vo = new OrderReservedListVo();
            vo.setId(item.getId());
            vo.setOriginalTime(item.getStartDateTime()+"~"+item.getEndDateTime());
            vo.setStatus(item.getStatus());

            vo.setOrderNumber(order.getOrderSn());
            vo.setTitle(orderGoods.getGoodsName());
            vo.setPrice(orderGoods.getGoodsPrice());

            // 订单信息
            JSONObject addressJson = JSONObject.parseObject(order.getAddress());
            String addressDetail = addressJson.getString("address");
            Customer customer = new Customer();
            customer.setName(order.getAddressContact());
            customer.setPhone(order.getAddressMobile());
            vo.setCustomer(customer);
            ServiceDetails serviceDetails = new ServiceDetails();
            serviceDetails.setServiceType(orderGoods.getGoodsName());
            serviceDetails.setScheduledTime(item.getStartDateTime()+"~"+item.getEndDateTime());
            serviceDetails.setServiceLocation(addressDetail);
            serviceDetails.setCustomerNote(item.getRemark());
            serviceDetails.setServiceFee(orderGoods.getGoodsPrice());


            vo.setServiceProgress(getServiceProgress(item.getId()));
            vo.setServiceDetails(serviceDetails);
            vo.setAddress(addressDetail);
            BeanUtils.copyProperties(item, vo);

            list.add(vo);
        }

        return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), list);
    }

    @Override
    public PageResult<CompletedListVo> completedList(PageValidate pageValidate, OrderAcceptSearchValidate searchValidate) {
        Integer page  = pageValidate.getPageNo();
        Integer limit = pageValidate.getPageSize();
        Integer userId = JzFrontThreadLocal.getUserId();
        QueryWrapper<OrderAccept> queryWrapper = new QueryWrapper<>();
        //已预约（服务中）
        if (StringUtils.isNotNull(searchValidate.getStatus())) {
            queryWrapper.eq("status", searchValidate.getStatus());
        }else {
            queryWrapper.ge("status", 4);
        }

        queryWrapper.eq("is_delete", 0).eq("user_id", userId).orderByDesc("create_time");


        IPage<OrderAccept> iPage = orderAcceptMapper.selectPage(new Page<>(page, limit), queryWrapper);

        List<CompletedListVo> list = new LinkedList<>();
        for(OrderAccept item : iPage.getRecords()) {
//            List<OrderGoods> orderGoodsList = orderGoodsMapper.selectList(new QueryWrapper<OrderGoods>().eq("order_id", record.getId()).select("id,goods_id,goods_name,goods_sku_id,goods_sku_value,goods_image,goods_num,goods_price," + "goods_original_price,need_pay_money,goods_money"));

            Order order = orderMapper.selectOne(new QueryWrapper<Order>().eq("id", item.getOrderId()).last("LIMIT 1"));
            OrderGoods orderGoods = orderGoodsMapper.selectOne(new QueryWrapper<OrderGoods>().eq("id", order.getId()).last("LIMIT 1"));



            CompletedListVo vo = new CompletedListVo();
            vo.setId(item.getId());
            vo.setServiceTime(item.getStartDateTime()+"~"+item.getEndDateTime());
            vo.setStatus(item.getStatus());

            vo.setOrderNumber(order.getOrderSn());
            vo.setTitle(orderGoods.getGoodsName());
            vo.setPrice(orderGoods.getGoodsPrice());

            // 订单信息
            JSONObject addressJson = JSONObject.parseObject(order.getAddress());
            String addressDetail = addressJson.getString("address");
            vo.setAddress(addressDetail);

            CustomerReview customerReview = new CustomerReview();
            customerReview.setContent(item.getEvaluate());
            customerReview.setRating(item.getRating());
            customerReview.setTime(TimeUtils.timestampToDate(item.getUpdateTime()));
            vo.setCustomerReview(customerReview);
            List<OrderTimeline> orderTimelineWithOrderDetails = getOrderTimelineWithOrderDetails(item.getId());
            vo.setOrderTimeline(orderTimelineWithOrderDetails);
            BeanUtils.copyProperties(item, vo);

            list.add(vo);
        }

        return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), list);
    }
    public List<OrderTimeline> getOrderTimelineWithOrderDetails(String orderAcceptId) {
        QueryWrapper<OrderAcceptDetails> orderAcceptDetailsQW = new QueryWrapper<>();
        orderAcceptDetailsQW.orderByDesc("status").eq("la_order_accept_id", orderAcceptId);

        List<OrderAcceptDetails> orderAcceptDetails = orderAcceptDetailsMapper.selectList(orderAcceptDetailsQW);

        List<OrderTimeline> orderTimelines = new ArrayList<>();
        for (OrderAcceptDetails orderDetail : orderAcceptDetails) {
            OrderTimeline timeline = new OrderTimeline();
            timeline.setAction(getActionByStatus(orderDetail.getStatus()));
            timeline.setTime(TimeUtils.timestampToDate(orderDetail.getCreateTime()));
            orderTimelines.add(timeline);
        }

        return orderTimelines;
    }

    /**
     * Helper method to map status code to action description
     */
    private String getActionByStatus(Integer status) {
        switch (status) {
            case 0: return "接单成功";
            case 1: return "已预约";
            case 2: return "已经出发";
            case 3: return "到达服务地点";
            case 4: return "开始服务";
            case 5: return "您提交了服务完成";
            case 6: return "客户确认完成";
            default: return "未知状态";
        }
    }
    ServiceProgress getServiceProgress(String orderAcceptId) {
        QueryWrapper<OrderAcceptDetails> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete", 0)
                .eq("la_order_accept_id", orderAcceptId)
                .orderByDesc("status")
                .ge("status", 1)
                .le("status", 5);

        List<OrderAcceptDetails> orderAcceptDetails = orderAcceptDetailsMapper.selectList(queryWrapper);

        ServiceProgress serviceProgress = new ServiceProgress();
        List<Step> steps = new ArrayList<>();

        // Initialize all steps as pending
        steps.add(new Step("已预约", "pending"));
        steps.add(new Step("已出发", "pending"));
        steps.add(new Step("到达地点", "pending")); // Fixed typo
        steps.add(new Step("服务中", "pending"));
        steps.add(new Step("已完成", "pending"));

        Integer maxStatus = 1;

        // Update step statuses based on database records
        if (!orderAcceptDetails.isEmpty()) {
            OrderAcceptDetails latestDetail = orderAcceptDetails.get(0);
            maxStatus = latestDetail.getStatus();

            // Map status values (1-5) to step indices (0-4)
            for (int i = 0; i < steps.size(); i++) {
                int stepStatus = i + 1; // Step status: 1-5
                if (stepStatus < maxStatus) {
                    steps.get(i).setStatus("completed");
                } else if (stepStatus == maxStatus) {
                    steps.get(i).setStatus("current");
                }
            }
        }

        serviceProgress.setStatus(maxStatus);
        serviceProgress.setSteps(steps);
        return serviceProgress;
    }


    /**
     * 接单详情
     *
     * @author LikeAdmin
     * @param id 主键参数
     * @return OrderAccept
     */
    @Override
    public OrderAcceptDetailVo detail(Integer id) {
        OrderAccept model = orderAcceptMapper.selectOne(
                new QueryWrapper<OrderAccept>()
                    .eq("id", id)
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在");

        OrderAcceptDetailVo vo = new OrderAcceptDetailVo();
        BeanUtils.copyProperties(model, vo);
        return vo;
    }

    /**
     * 接单新增
     *
     * @author LikeAdmin
     * @param createValidate 参数
     */
    @Override
    public void add(OrderAcceptCreateValidate createValidate) {
        String orderAcceptId = ServiceUtils.getUUID();
        OrderAccept model = new OrderAccept();
        Integer userId = JzFrontThreadLocal.getUserId();
        //订单id
        model.setId(orderAcceptId);
        model.setOrderId(createValidate.getOrderId());
        model.setUserId(userId);
        model.setStatus(0);
        model.setCreateTime(System.currentTimeMillis() / 1000);
        model.setUpdateTime(System.currentTimeMillis() / 1000);
       //订单详情
        OrderAcceptDetails orderADetails = new OrderAcceptDetails();
        orderADetails.setLaOrderAcceptId(orderAcceptId);
        orderADetails.setCreateTime(System.currentTimeMillis() / 1000);
        orderADetails.setStatus(0);
        orderAcceptDetailsMapper.insert(orderADetails);

       //修改订单状态已接单
        Order order = new Order();
        order.setId(createValidate.getOrderId());
        order.setOrderStatus(3);
        order.setUpdateTime(System.currentTimeMillis() / 1000);
        orderMapper.updateById(order);

        orderAcceptMapper.insert(model);
    }
    //立刻接单
    @Override
    public void appointment(OrderAcceptCreateValidate createValidate) {
        OrderAccept model = new OrderAccept();
        Integer userId = JzFrontThreadLocal.getUserId();
        //订单id
        model.setId(createValidate.getId());
        model.setStatus(3);
        model.setStartDateTime(createValidate.getStartDateTime());
        model.setEndDateTime(createValidate.getEndDateTime());
        model.setUpdateTime(System.currentTimeMillis() / 1000);
        orderAcceptMapper.updateById(model);

        OrderAcceptDetails orderADetails = new OrderAcceptDetails();
        orderADetails.setLaOrderAcceptId(createValidate.getId());
        orderADetails.setCreateTime(System.currentTimeMillis() / 1000);
        orderADetails.setStatus(1);
        orderAcceptDetailsMapper.insert(orderADetails);
    }

    @Override
    public void receivePayment(OrderAcceptCreateValidate createValidate) {
        OrderAccept model = new OrderAccept();
        Integer userId = JzFrontThreadLocal.getUserId();
        //订单id
        model.setId(createValidate.getId());
        model.setStatus(6);
        model.setOfflineMoney(createValidate.getOfflineMoney());
        model.setUpdateTime(System.currentTimeMillis() / 1000);
        orderAcceptMapper.updateById(model);

//        OrderAcceptDetails orderADetails = new OrderAcceptDetails();
//        orderADetails.setLaOrderAcceptId(createValidate.getId());
//        orderADetails.setCreateTime(System.currentTimeMillis() / 1000);
//        orderADetails.setStatus(1);
//        orderAcceptDetailsMapper.insert(orderADetails);
    }

    /**
     * 接单编辑
     *
     * @author LikeAdmin
     * @param updateValidate 参数
     */
    @Override
    public void edit(OrderAcceptUpdateValidate updateValidate) {
        OrderAccept model = orderAcceptMapper.selectOne(
                new QueryWrapper<OrderAccept>()
                    .eq("id",  updateValidate.getId())
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在!");


        model.setAdminId(updateValidate.getAdminId());
        model.setOrderSn(updateValidate.getOrderSn());
        model.setContact(updateValidate.getContact());
        model.setMobile(updateValidate.getMobile());

        model.setRemark(updateValidate.getRemark());
        model.setEvaluate(updateValidate.getEvaluate());
        model.setRating(updateValidate.getRating());
        model.setUpdateTime(System.currentTimeMillis() / 1000);
        orderAcceptMapper.updateById(model);
    }

    /**
     * 接单删除
     *
     * @author LikeAdmin
     * @param id 主键ID
     */
    @Override
    public void del(Integer id) {
        OrderAccept model = orderAcceptMapper.selectOne(
                new QueryWrapper<OrderAccept>()
                    .eq("id", id)
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在!");

        orderAcceptMapper.delete(new QueryWrapper<OrderAccept>().eq("id", id));
    }

}
